#include <Arduino.h>
#include <ESP8266WiFi.h>
#include <FS.h>
#include <LittleFS.h>
#include <ESPAsyncTCP.h>
#include <ESPAsyncWebServer.h>
#include <ArduinoJson.h>

AsyncWebServer server(80);

const char *ssid = "";
const char *pswd = "";
const char *ssidFile = "/ssid.json";

// webserver配置程序
void handleWiFiConfig()
{
  if (!LittleFS.begin())
  {
    Serial.println("LittleFS  initialization failed!");
    return;
  }

  // 访问index.html首页
  server.on("/", HTTP_GET, [](AsyncWebServerRequest *request)
            {
    Serial.println("开始判断首页文件是否存在");
    // 检查SPIFFS文件系统中是否存在index.html文件
    if (LittleFS.exists("/index.html"))
    {
      fs::File file = LittleFS.open("/index.html", "r");
       // 打开index.html
        if (file)
        {
          String fileContent;

          // 逐字节读取文件内容
          while (file.available())
          {
            fileContent += (char)file.read();
          }
          file.close(); // 关闭文件

          // 返回HTML内容
          Serial.println(fileContent);
          request->send(200, "text/html", fileContent);
          return;
        }
      
    }
    // 如果文件不存在，返回404错误
    request->send(404, "text/plain", "Not found"); });

  // 进入wifi配置页面,填上wifi名和密码，提交
  server.on("/setting", HTTP_GET, [](AsyncWebServerRequest *request)
            {
Serial.println("开始判断setting文件是否存在");
// 检查SPIFFS文件系统中是否存在setting.html文件
if (LittleFS.exists("/setting.html"))
{
fs::File file = LittleFS.open("/setting.html", "r");
{ // 打开setting.html
if (file)
{
String fileContent;

// 逐字节读取文件内容
while (file.available())
{
fileContent += (char)file.read();
}
file.close(); // 关闭文件

// 返回HTML内容
Serial.println(fileContent);
request->send(200, "text/html", fileContent);
return;
}
}
}
// 如果文件不存在，返回404错误
request->send(404, "text/plain", "Not found"); });

  // 将提交的ssid和密码，存到ssidFile文件中，进行wifi连接，并在页面显示连接中
  server.on("/connect", HTTP_POST, [](AsyncWebServerRequest *request)
            {
    String ssid = request->getParam("ssid",true)->value();
    String pswd = request->getParam("pswd",true)->value();

    JsonDocument doc;
    doc["ssid"] = ssid;
    doc["pswd"] = pswd;
    fs::File file = LittleFS.open(ssidFile,"w");
    if(file){
      serializeJson(doc,file);
      file.close();
    }

    WiFi.begin(ssid.c_str(), pswd.c_str());
    request->send(200, "text/html", "<h1>Connecting...</h1>"); });

  server.begin();
}

// 从ssidFile加载文件内容，如果有内容，进行wifi连接，成功则输出IP。
void loadWiFiConfig()
{
  if (LittleFS.begin())
  {
    fs::File file = LittleFS.open(ssidFile, "r");
    if (file)
    {
      JsonDocument doc;
      DeserializationError error = deserializeJson(doc, file);
      if (!error)
      {
        String ssid = doc["ssid"];
        String pswd = doc["pswd"];
        // Serial.println(ssid);
        // Serial.println(pswd);
        WiFi.begin(ssid.c_str(), pswd.c_str());
        unsigned long startTime = millis();
        while (WiFi.status() != WL_CONNECTED && millis() - startTime < 10000)
        { // wifi连接中
          delay(500);
          Serial.print(".");
        }
        if (WiFi.status() != WL_CONNECTED)
        {
          Serial.println("WiFi connect failed,Starting captive portal...");
          handleWiFiConfig();
        }
        else
        {
          Serial.println("WiFi connected");
          Serial.println(WiFi.localIP());
        }
      }
      file.close();
    }
  }
}

void setup()
{
  Serial.begin(9600);
  // 设置WiFi为热点模式
  WiFi.softAP(ssid, pswd);
  Serial.println("热点已启动");
  Serial.print("访问地址:");
  Serial.println(WiFi.softAPIP());

  // 加载wifi配置
  loadWiFiConfig();

  if (WiFi.status() != WL_CONNECTED)
  {
    Serial.println("Starting captive portal...");
    handleWiFiConfig();
  }
  else
  {
    handleWiFiConfig();
    Serial.println("WiFi connected");
  }
}

void loop()
{
}